package com.zheng.admin.config;

import com.google.gson.Gson;
import com.zheng.admin.dto.AdminResp;
import com.zheng.admin.exception.AdminSystemException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zcz on 2017/11/6.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    Gson gson = new Gson();

    @ExceptionHandler(value = AdminSystemException.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, AdminSystemException exception) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.endsWith(".html")) {
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", exception);
            mav.addObject("url", requestURI);
            mav.setViewName("error");
            return mav;
        } else {
            AdminResp errorResp = new AdminResp(exception.getCode(), exception.getMessage());
            response.getWriter().write(gson.toJson(errorResp));
            response.getWriter().flush();
            return null;
        }
    }
}
